﻿/*
Copyright (c) 2013, Bartłomiej Gałkowski
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: 

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer. 
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace PyroGen
{

    internal sealed class CodeTextBox : RichTextBox
    {
        private bool _containsOnlyErrorText;

        private readonly List<Tuple<int, int>> _selectionStack;

        private readonly TextHistory _history;

        public CodeTextBox()
            : this(false, null)
        { }

        public CodeTextBox(bool containsOnlyErrorText,ContextMenuStrip cmenu)
        {
            _containsOnlyErrorText = containsOnlyErrorText;
            _selectionStack = new List<Tuple<int, int>>();
            ShortcutsEnabled = false;
            _history = new TextHistory();
            Font = new Font(new FontFamily("Courier New"), 10.0f, FontStyle.Regular);
            Dock = DockStyle.Fill;
            WordWrap = false;
            BorderStyle = BorderStyle.None;
            this.ContextMenuStrip = cmenu;
            OnTextChanged(null);

        }


        [DllImport("user32.dll")]
        private extern static IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

        [DllImport("user32.dll")]
        static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

        [DllImport("user32.dll")]
        static extern int GetScrollPos(IntPtr hWnd, int nBar);

        private void StopPaint()
        {
            SendMessage(Handle, 0xb, (IntPtr)0, IntPtr.Zero);
        }

        private void StartPaint()
        {
            SendMessage(Handle, 0xb, (IntPtr)1, IntPtr.Zero);
            Refresh();
        }


        private void PushSelection()
        {
            _selectionStack.Add(new Tuple<int, int>(SelectionStart, SelectionLength));


        }

        private void PopSelection()
        {
            if (_selectionStack.Count > 0)
            {
                int last = _selectionStack.Count - 1;
                Select(_selectionStack[last].Item1, _selectionStack[last].Item2);

                _selectionStack.RemoveAt(last);
            }
        }

        private void ClearColorization()
        {

            SelectAll();
            SelectionBackColor = Color.White;
            SelectionColor = Color.Black;

        }

        private void HiglightKeywords()
        {

            //string[] tokens = Text.Split(new char[] { '(', ')', '\n', '\t', ' ', ';', '{', '}', '[', ']' },
            //                             StringSplitOptions.RemoveEmptyEntries);

            char[] wspbrk = new char[] { '(', ')', '\n', '\t', '\r', ';', '{', '}', '[', ']','+','=','/','\"','*','%','?','&','^'};
            
            string SimpleText = " " +String.Copy(Text)+ " ";

            foreach (char s in wspbrk)
                SimpleText = SimpleText.Replace(s, ' ');

            List<string> keywords = new List<string>()
                                        {
                                            "private",
                                            "public",
                                            "using",
                                            "new",
                                            "static",
                                            "class",
                                            "namespace",
                                            "foreach",
                                            "return",
                                            "virtual",
                                            "assembly", "property", "include",
                                            "language", "execute", "dim", "as", "end", "next", "is", "for"
                                        };
            List<string> types = new List<string>() { "void", "int", "string", "float", "double", "char" };

            foreach (string keyword in keywords.Concat(types))
            {
                int i = 0;
                while ((i = SimpleText.IndexOf(' '+keyword+' ', i)) > 0)
                {

                    SelectionStart = i;
                    SelectionLength = keyword.Length;
                    if (types.Contains(keyword))
                        SelectionColor = Color.DarkBlue;
                    else
                        SelectionColor = Color.Blue;
                    i++;
                }
            }


        }

        private void HighlightMetaKeywords()
        {

            PositionFinder pf = new PositionFinder(Text);

            pf.AddAllPositions(SettingsLoader.LoadDefaultTags());

            for (int i = 1; i + 1 < pf.BorderPositions.Count; i += 2)
            {
                Select(pf.BorderPositions[i].Start, pf.BorderPositions[i + 1].End - pf.BorderPositions[i].Start);
                switch (pf.BorderPositions[i].Type)
                {
                    case CodeType.Code:
                    case CodeType.ScriptCode:
                        SelectionBackColor = Color.FromArgb(230, 255, 230);
                        break;
                    case CodeType.ConfigCode:
                        SelectionBackColor = Color.FromArgb(255, 230, 230);
                        break;
                    case CodeType.Expression:
                        SelectionBackColor = Color.FromArgb(230, 230, 255);
                        break;
                }
            }


        }

        private void RestoreState(TextHistory.HistoryItem item)
        {
            Text = item.Text;
            SelectionLength = item.SelectionLength;
            SelectionStart = item.SelectionStart;

            //ScrollToCaret();
        }


        public new void Undo()
        {
            if (!_history.Empty())
                RestoreState(_history.Undo());
        }

        public new void Redo()
        {
            if (!_history.Empty())
                RestoreState(_history.Redo());
        }



        protected override void OnTextChanged(EventArgs e)
        {

            _history.Add(String.Copy(Text), SelectionStart, SelectionLength);


            if (!_containsOnlyErrorText)
            {
                StopPaint();
                PushSelection();
                ClearColorization();
                HighlightMetaKeywords();
                HiglightKeywords();
                PopSelection();
                StartPaint();
            }
        }
    }


    // TODO: Simplifiy
    public class TextHistory
    {
        public struct HistoryItem
        {
            public readonly string Text;
            public readonly int SelectionStart;
            public readonly int SelectionLength;

            public HistoryItem(string text, int selectionStart, int selectionLength)
            {
                Text = text;
                SelectionStart = selectionStart;
                SelectionLength = selectionLength;
            }
        }

        private readonly List<HistoryItem> _history;
        private int _currIndex;


        public TextHistory()
        {
            _history = new List<HistoryItem>(100);
            _currIndex = 0;
        }

        public bool Empty()
        {
            return _history.Count == 0;
        }

        public HistoryItem Undo()
        {
            if (_currIndex <= 0)
                return new HistoryItem("", 0, 0);

            if (_currIndex > 0)
                _currIndex --;

            if (_currIndex - 1 > 0)
            {
                return _history[_currIndex - 1];
            }
            return _history[_currIndex];
        }

        public HistoryItem Redo()
        {
            if (_currIndex >= _history.Count) // - 1
                return _history[_history.Count - 1];

            if (_currIndex + 1 < _history.Count)
                _currIndex ++;

            return _history[_currIndex - 1];
        }

        public void Add(string item, int selectionStart, int selectionLength)
        {
            if (_history.Count == 0 || !(_history[_currIndex - 1].Text.Equals(item)))
            {
                if (_currIndex < _history.Count)
                    _history.RemoveRange(_currIndex, _history.Count - _currIndex);


                if (_history.Count + 1 < _history.Capacity)
                    _currIndex++;
                else
                    _history.RemoveAt(0);

                _history.Add(new HistoryItem(item, selectionStart, selectionLength));
            }
        }
    }


  
}